package javazoom.jlme.util;


import javax.sound.sampled.SourceDataLine;
import javax.sound.sampled.DataLine;
import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.LineUnavailableException;
import java.io.InputStream;
import javazoom.jlme.decoder.Decoder;
import javazoom.jlme.decoder.Header;
import javazoom.jlme.decoder.SampleBuffer;
import javazoom.jlme.decoder.BitStream;


public class Player {
  private Decoder decoder;
  private SourceDataLine line;
  private BitStream bitstream;
  public boolean playable = true;
  public boolean stopped = false;
  //Runtime rt = null;


  public Player(InputStream stream) throws Exception {
    bitstream = new BitStream(stream);
    //rt = Runtime.getRuntime();
  }


  public void startOutput(AudioFormat playFormat) throws LineUnavailableException {
    DataLine.Info info= new DataLine.Info(SourceDataLine.class, playFormat);

    if (!AudioSystem.isLineSupported(info)) {
      throw new LineUnavailableException("sorry, the sound format cannot be played");
    }
    line = (SourceDataLine)AudioSystem.getLine(info);
    line.open(playFormat);
    line.start();
  }


  public void stopOutput() {
    if (line != null)
    {
		line.drain();
		line.stop();
		line.close();
		line = null;
    }
  }
  public void play() throws Exception {
    boolean first = true;
    int length;
    Header header = bitstream.readFrame();
    decoder = new Decoder(header, bitstream);
    while (playable)
    {
      try
      {
      	SampleBuffer output = (SampleBuffer)decoder.decodeFrame();
      	length = output.size();
      	if (length == 0) break;
      	//{
      		if (first)
      		{
      		  first = false;
      		  startOutput(new AudioFormat(decoder.getOutputFrequency(), 16, decoder.getOutputChannels(), true, false));
      		}
      		line.write(output.getBuffer(), 0, length);
      		bitstream.closeFrame();
      		header = bitstream.readFrame();
      		//System.out.println("Mem:"+(rt.totalMemory() - rt.freeMemory())+"/"+rt.totalMemory());
      	//}
	  } catch (Exception e)
	  	{
		e.printStackTrace();
			break;
		}
    }
    playable = false;
	stopOutput();
    bitstream.close();
  }

  public void stop() {
      stopped= true;
    playable = false;
  }
}
